#!/usr/bin/env python
# encoding: utf-8

import gdata.photos.service
import logging

class Account(object):
  def __init__(self, email, password):
    self.email = email
    self.client = gdata.photos.service.PhotosService()
    self.client.email = email
    self.client.password = password
    self.client.source = 'nedajil-scripts-1'
    logging.info("Authenticating as '%s'" % email)
    self.client.ProgrammaticLogin()
    
  def GetAlbums(self):
    logging.info("Fetching the list of albums")
    return [Album(self, album)
            for album in self.client.GetUserFeed(user=self.email).entry]
            
  def NewAlbum(self, title):
    logging.info("Creating an album '%s'" % title)
    return Album(self, self.client.InsertAlbum(title=title,
                                               summary=""))
            
class Album(object):
  MAX_PHOTOS_IN_ALBUM = 500

  def __init__(self, account, album):
    self.account = account
    self.album = album
    self.album_url = \
        '/data/feed/api/user/default/albumid/%s' % self.album.gphoto_id.text
    self.client = account.client
    
  def Delete(self):
    logging.info("Deleting the album '%s'" % self.album.title.text)
    self.client.Delete(self.album)
    
  def UploadPhoto(self, filename):
    logging.info("Uploading photo '%s'" % filename)
    try:
      photo = self.client.InsertPhotoSimple(self.album_url, filename, '', filename,
                                            content_type='image/jpeg')
      self.album.numphotos.text = str(int(self.album.numphotos.text) + 1)
      return photo
    except Exception, ex:
      logging.warning("Error: %s" % ex)

  def NumPhotos(self):
    return int(self.album.numphotos.text)
    
  def Full(self):
    return self.NumPhotos() == self.MAX_PHOTOS_IN_ALBUM
